<?php

class Transaction {

	protected $table = 'foria_transaction';
	protected $tr_table	= '';
	protected $db		= null;
	public $mtime	= 0;

	function __construct($params)
	{
		$this->tr_table = $params['tr_table'];
		$this->ci = &get_instance();
		$this->db = &$this->ci->db;
		$this->mtime = microtime (true);
	}	

	/*
	
	*/
	function insert ($operation = "", $id = 0, $json = '', $win_id = '')
	{
		$data = array(
			'tr_table' => $this->tr_table,
			'mtime' => $this->mtime,
			'operation' => $operation,
			'id' => $id,
			'json' => $json
        );
		$this->db->insert($this->table, $data);
		if ($this->db->affected_rows() == 1)
			return $this->db->insert_id();
		return false;
		
	}
	
	function fetch ($lmtime)
	{
		$ret = array();
		$this->db->where('mtime >=', (float)$lmtime);
		$this->db->where('tr_table', $this->tr_table);
		$this->db->order_by("mtime", "asc"); 
		$query = $this->db->get($this->table);
		if ($query->num_rows()>0)
		{
			foreach ($query->result_array() as $row)
			{
				$ret[] = json_decode($row['json']);
			}
		}
		return $ret;
	}

	function garbage ($lmtime)
	{
		$this->db->where('mtime<'.$lmtime);
		$this->db->delete($this-table); 		
	}
	
}

/* TEST ONLY */
/*
$param = array ('table'=>'foria_pages');

for ($i = 0; $i <= 100; $i++)
{
	$TR = new Transaction ($param);
	$TR.insert ('Operation '.$i, $i, 'JSON '.$i);
	unset ($TR);
}
*/
/* END TEST */